package yancy.modules.sys.controller;

import yancy.common.annotation.SysLog;
import yancy.common.utils.Constant;
import yancy.common.utils.PageUtils;
import yancy.common.utils.R;
import yancy.common.validator.ValidatorUtils;
import yancy.common.validator.group.AddGroup;
import yancy.common.validator.group.UpdateGroup;
import yancy.modules.sys.entity.SysBook;
import yancy.modules.sys.entity.SysBorrowBook;
import yancy.modules.sys.service.SysBookAuthorService;
import yancy.modules.sys.service.SysBookService;
import yancy.modules.sys.service.SysBorrowBookService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sys/borrow")
@AllArgsConstructor
public class SysBorrowBookController extends AbstractController {

    private final yancy.modules.sys.service.SysBookService SysBookService;
    private final SysBookService bookService;
    private final SysBorrowBookService borrowBookService;
    private final SysBookAuthorService bookAuthorService;


    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        //只有超级管理员，才能查看所有管理员列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            params.put("createUserId", getUserId());
        }
        PageUtils page = bookService.queryPage(params);


        return R.ok().put("page", page);
    }


    /**
     * 用户信息
     */
    @GetMapping("/info/{bookId}")
    public R info(@PathVariable("bookId") Long bookId) {
        SysBook book = bookService.getById(bookId);

        //获取用户所属的角色列表
        List<Long> bookIdList = bookAuthorService.queryAuthorIdList(bookId);
        book.setAuthorIdList(bookIdList);

        return R.ok().put("book", book);
    }


    /**
     * 保存用户
     */
    @SysLog("保存图书")
    @PostMapping("/save")
    public R save(@RequestBody SysBook book) {
        ValidatorUtils.validateEntity(book, AddGroup.class);

        book.setCreateUserId(getUserId());
        book.setCreateTime(new Date());
        bookService.saveBook(book);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")

    public R update(@RequestBody SysBorrowBook borrowBook) {
        ValidatorUtils.validateEntity(borrowBook, UpdateGroup.class);
        borrowBook.setCreateUserId(getUserId());
        borrowBook.setUserId(getUserId());
        borrowBook.setNeedBack(borrowBook.getTotal());
        borrowBook.setCreateTime(new Date());
        borrowBookService.borrow(borrowBook);
        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    public R delete(@RequestBody Long[] bookIds) {

        return R.ok();
    }

}
